import Vue from 'vue'
import IM from '@/im'
import { getParentListApi, getTeacherListApi } from '@/api/contact/index'

const { Conversation, ConversationType } = IM

const im = {
  state: () => ({
    userId: '', // 当前用户userId
    users: [], // 所有用户
    conversations: {}, // 所有会话
    boundPersons: [] // 已绑定人列表
  }),
  mutations: {
    SET_USERID: (state, payload) => {
      state.userId = payload
    },
    SET_CONVERSATION: (state, payload) => {
      const { key, value } = payload

      Vue.set(state.conversations, key, value)
    },
    UPDATE_CONVERSATION_Message_Sent(state, message) {
      const { targetId } = message
      const conversation = state.conversations[targetId]

      const save = () => {
        if (!conversation) {
          return
        }

        conversation.messages.push(message)
        conversation.unreadMessageCount += 1
      }
      save()
    },
    UPDATE_CONVERSATION_Message_Received(state, message) {
      const { targetId } = message
      const conversation = state.conversations[targetId]

      const save = () => {
        if (!conversation) {
          setTimeout(() => {
            save()
          }, 1000)
          return
        }

        conversation.messages.push(message)
        conversation.unreadMessageCount += 1
      }

      save()
    },
    UPDATE_CONVERSATION_Unread_Message_Count(state, payload) {
      const { targetId, unreadMessageCount } = payload
      const conversation = state.conversations[targetId]
      conversation.unreadMessageCount = unreadMessageCount
    }
  },
  actions: {
    InitContacts({ commit, state, getters }, payload) {
      const { imEngine } = payload
      Promise.all([getParentListApi(), getTeacherListApi()]).then(async (res) => {
        const [parentRes,teacherRes, ] = res
        const { data: parentPersons } = parentRes
        const { data: teacherPersons } = teacherRes
        let users = []
        let boundPersons = []
        if (Array.isArray(parentPersons) && parentPersons.length > 0) {
          users = [
            {
              name: parentPersons[0].studentName,
              userId: parentPersons[0].studentImId
            }
          ]

          parentPersons.forEach((person) => {
            users.push({
              name: person.userName,
              userId: person.userImId,
              phone: person.userName.replace('用户', ''),
              miniOpenid: person.miniOpenid,
              relationshipType: person.relationshipType
            })
          })
          boundPersons = parentPersons
        }
        if(Array.isArray(teacherPersons) && teacherPersons.length > 0) {
          let teacherList = []
          teacherPersons.forEach((item) => {
            let teachers = item.userRespVOS
            if(Array.isArray(teachers) && teachers.length > 0){
              teachers.forEach((teacher) => {
                teacherList.push(teacher)
              })
            }
          })
          teacherList = teacherList.filter((item, index, self) => {
            return self.findIndex((t) => t.id === item.id) === index
          })
          teacherList.forEach((person) => {
            users.push({
              name: person.nickname,
              userId: person.userImId,
              phone: person.mobile,
              miniOpenid: '',
              relationshipType: '',
            })
          })
          boundPersons = boundPersons.concat(teacherList)
        }
          state.users = users
          state.boundPersons = boundPersons

          // 加载所有会话
          for (const person of boundPersons) {
            const conversationType = ConversationType.PRIVATE
            const { userImId: targetId } = person

            imEngine.getConversation({
              conversationType: 1,
              targetId,
              channelId: null
            })
          }
      })
    }
  }
}

export default im
